<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="params.name" placeholder="请输入内容" class="search-main" clearable @clear="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>

    <el-button type="primary" style="margin: 10px 5px;" size="medium" @click="addBuilding">添加楼宇</el-button>
    <el-button style="margin: 10px 5px;" size="medium" @click="exportToExcel">导出Excel</el-button>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="buildingList"
      >
        <el-table-column
          prop="index"
          label="序号"
          type="index"
        />
        <el-table-column
          prop="name"
          label="楼宇名称"
          width="180"
        />
        <el-table-column
          prop="floors"
          label="层数"
        />
        <el-table-column
          prop="area"
          label="在管面积(m²)"
          width="120"
        />
        <el-table-column
          prop="propertyFeePrice"
          label="物业费(元/m²)"
          width="120"
        />
        <el-table-column
          prop="status"
          label="状态"
        >
          <template #default="scope">
            <el-button
              round
              size="mini"
              :type="formatButton(formatStatus(scope.row.status))"
            >
              {{ formatStatus(scope.row.status) }}
            </el-button>

          </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template #default="scope">

            <el-button
              size="mini"
              type="text"
              @click="edit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="confirmDel(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加楼宇弹框 -->
    <el-dialog
      title="添加楼宇"
      :visible.sync="dialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="100px">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model.number="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import {
  getBuildingListAPI,
  createBuildingListAPI,
  delBuildingListAPI,
  editBuildingListAPI
} from '@/api/building'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    // 物业价格
    const checkPrice = (rule, value, callback) => {
      const pricePattern = /^\d+$/
      if (pricePattern.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的物业价格(数字类型)'))
      }
    }

    const checkArea = (rule, value, callback) => {
      const pricePattern = /^\d+$/
      if (pricePattern.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的在管面积(数字类型)'))
      }
    }
    const checkFloors = (rule, value, callback) => {
      const pricePattern = /^\d+$/
      if (pricePattern.test(value)) {
        if (value > 0 && value <= 20) {
          callback()
        } else {
          callback(new Error('楼宇层数需在1-20之间'))
        }
      } else {
        callback(new Error('请输入正确的楼宇层数(数字类型)'))
      }
    }
    return {
      buildingList: [],
      params: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      total: 0,
      dialogVisible: false,
      addForm: {
        name: '',
        floors: '',
        area: '',
        propertyFeePrice: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' },
          { validator: checkFloors, trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' },
          { validator: checkArea, trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入楼宇物业费', trigger: 'blur' },
          { validator: checkPrice, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getBuildingList()
  },
  methods: {
    async getBuildingList() {
      const res = await getBuildingListAPI(this.params)
      this.buildingList = res.data.rows
      this.total = res.data.total
    },

    // 格式化状态
    formatStatus(status) {
      const MAP = {
        0: '闲置中',
        1: '租赁中'
      }
      return MAP[status]
    },
    formatButton(str) {
      const MAP = {
        '租赁中': 'danger',
        '闲置中': 'success'
      }
      return MAP[str]
    },
    handleCurrentChange(value) {
      this.params.page = value
      this.getBuildingList()
    },
    doSearch() {
      this.params.page = 1
      this.getBuildingList()
    },
    addBuilding() {
      this.dialogVisible = true
    },
    closeDialog() {
      this.$refs.addForm.clearValidate()
      this.clearForm()
      this.dialogVisible = false
    },
    confirmAdd() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          if (this.addForm.id) {
            await editBuildingListAPI(this.addForm)
          } else {
            if (!this.addForm.id) {
              delete this.addForm.id
            }

            await createBuildingListAPI(this.addForm)
          }

          this.getBuildingList()
          this.$message({
            type: 'success',
            message: `${this.addForm.id ? '编辑' : '添加'}楼宇成功`
          })
          this.dialogVisible = false
        }
      })
    },
    confirmDel(id) {
      const flag = this.buildingList.find(k => k.id === id && k.status === 1)
      if (flag) {
        this.$message({
          type: 'error',
          message: '租赁中的楼宇不允许删除'
        })
        return
      }
      this.$confirm('你确定要删除该楼宇吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delBuildingListAPI(id)
        this.getBuildingList()
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      })
    },
    edit(row) {
      this.dialogVisible = true
      const { id, area, floors, name, propertyFeePrice } = row
      this.addForm = { id, area, floors, name, propertyFeePrice }
    },

    clearForm() {
      this.addForm = {
        id: '',
        name: '',
        floors: '',
        area: '',
        propertyFeePrice: ''
      }
    },
    // 导出excel
    async exportToExcel() {
      const res = await getBuildingListAPI(this.params)
      // 表头英文字段
      const tableHeaderKeys = ['name', 'floors', 'area', 'propertyFeePrice', 'status']
      // 表头中文value
      const tableHeadervalues = ['楼宇名称', '层数', '在管面积(㎡)', '物业费(㎡)', '状态']
      const sheetData = res.data.rows.map(item => {
        const _item = {}
        tableHeaderKeys.forEach(key => {
          if (key === 'status') {
            _item[key] = item[key] ? '租赁中' : '闲置中'
          } else {
            _item[key] = item[key]
          }
        })
        return _item
      })

      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeadervalues], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container{
  padding:10px;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237,237,237,.9);;
  padding-bottom: 20px;
  .search-label{
    width:100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}

.page-container{
    padding:4px 0px;
    text-align: right;
  }
</style>
